package com.dingding.thirdpartydingding.service;

import com.alibaba.fastjson.JSONObject;
import com.dingding.thirdpartydingding.util.DingDingProperties;
import com.dingding.thirdpartydingding.util.RedisUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author zjd
 * @Title:
 * @Description:
 * @date 2021/6/914:43
 */
@Service
public class PersonnelServiceImpl implements PersonnelService{

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public String findByUserId(String userId,String language) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userId);
            req.setLanguage(language);
            OapiV2UserGetResponse rsp = client.execute(req, getToken());
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getToken() {
        try {
            String ding_ding_token = (String)redisUtils.get("Ding_Ding_Token");
            if (ding_ding_token!=null){
                return ding_ding_token;
            }
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setHttpMethod("GET");
            req.setAppkey(DingDingProperties.getAppKey());
            req.setAppsecret(DingDingProperties.getAppSecret());
            OapiGettokenResponse rsp = client.execute(req);
            if (rsp.isSuccess()){
                JSONObject  jsonObject = JSONObject.parseObject(rsp.getBody());
                Map<String,Object> map = (Map<String,Object>)jsonObject;//json对象转Map
                redisUtils.set("Ding_Ding_Token",map.get("access_token"),60*60*2);
            }
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
